<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { TodoItemsForm } from '#/api/hm/todoItems/model';

import { computed, onMounted } from 'vue';

import { useAccess } from '@vben/access';
import { Page, useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';
import { getVxePopupContainer } from '@vben/utils';

import { Modal, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { paymentAdjustmentReject } from '#/api/hm/paymentAdjustment';
import {
  processingAgent,
  todoItemsExport,
  todoItemsList,
  todoItemsRemove,
} from '#/api/hm/todoItems';
import { userList } from '#/api/system/user';
import { commonDownloadExcel } from '#/utils/file/download';

import todoDetailModal from './component/todo-detail-modal.vue';
import todoItemInfo from './component/todo-item-info.vue';
import { columns, querySchema } from './data';
import todoItemsModal from './todoItems-modal.vue';

const userStore = useUserStore();

const { hasAccessByRoles } = useAccess();
const isLeader = computed(() => {
  return hasAccessByRoles(['dept-manage', 'shop-owner', 'ceo']);
});
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin', 'ceo']);
});

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
  // 不需要直接删除
  fieldMappingTime: [
    [
      'todoCompletionTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD', 'YYYY-MM-DD'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await todoItemsList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'todoId',
    // 鼠标悬停高亮
    isHover: true,
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'hm-todoItems-index',
};

// const checked = ref(false);
const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [TodoItemsModal, modalApi] = useVbenModal({
  connectedComponent: todoItemsModal,
});

const [TodoItemsInfoModal, infoModalApi] = useVbenModal({
  connectedComponent: todoItemInfo,
});

const [TodoDetailModal, detailModalApi] = useVbenModal({
  connectedComponent: todoDetailModal,
});

function handleAdd() {
  modalApi.setData({});
  modalApi.open();
}

async function processingAgentEdit(row: Required<TodoItemsForm>) {
  modalApi.setData({
    id: row.todoId,
    outRecordId: row.todoOutboundOrder,
    edit: false,
  });
  modalApi.open();
}

async function handleEdit(row: Required<TodoItemsForm>) {
  modalApi.setData({
    id: row.todoId,
    outRecordId: row.todoOutboundOrder,
    edit: true,
  });
  modalApi.open();
}

async function todoInfo(row: Required<TodoItemsForm>, isLeader: boolean) {
  infoModalApi.setData({ id: row.todoId, isLeader });
  infoModalApi.open();
}

// 查看详情
function handleViewDetail(row: Required<TodoItemsForm>) {
  detailModalApi.setData({ id: row.todoId });
  detailModalApi.open();
}

function handleReject(row: Required<TodoItemsForm>) {
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认驳回该条代办？`,
    onOk: async () => {
      // 特殊处理：回款调整待办
      if (row.todoType === '9') {
        // 从 remark 中提取 adjustmentId
        const adjustmentId = row.remark?.match(/adjustmentId:(\d+)/)?.[1];

        if (adjustmentId) {
          try {
            // 调用专用的驳回接口
            await paymentAdjustmentReject(adjustmentId, '待办驳回');
            await tableApi.query();
            return;
          } catch (error) {
            console.error('回款调整驳回失败:', error);
            throw error;
          }
        }
      }

      // 原有的处理逻辑
      const params = {
        ...row,
        status: '2',
      };
      await processingAgent(params);
      await tableApi.query();
    },
  });
}

async function handleDelete(row: Required<TodoItemsForm>) {
  console.log('ccccc');
  await todoItemsRemove(row.todoId);
  await tableApi.query();
}

function handleDownloadExcel() {
  commonDownloadExcel(
    todoItemsExport,
    '代办事项数据',
    tableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}

// 查询待办人列表
onMounted(async () => {
  const ret = await userList({ pageNum: 1, pageSize: 999 });
  const userOptions = ret.rows.map((row) => ({
    label: row.userName,
    value: row.userId,
  }));
  const columns = [];
  columns.push(...userOptions);
  tableApi.formApi.updateSchema([
    {
      fieldName: 'todoPersonId',
      componentProps: {
        options: columns,
      },
    },
  ]);
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="待办事项列表">
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['hm:todoItems:export']"
            @click="handleDownloadExcel"
          >
            {{ $t('pages.common.export') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['hm:todoItems:add']"
            @click="handleAdd"
          >
            {{ $t('回访') }}
          </a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['hm:todoItems:query']"
            @click="handleViewDetail(row)"
          >
            查看
          </ghost-button>
          <ghost-button
            v-if="
              row.status === '0' &&
              (row.todoPersonId === userStore.userInfo?.userId || isAdmin)
            "
            style="color: #e69202"
            v-access:code="['hm:todoItems:edit']"
            @click="processingAgentEdit(row)"
          >
            处理
          </ghost-button>
          <ghost-button
            v-if="row.status === '1' && isAdmin"
            style="color: #e69202"
            v-access:code="['hm:todoItems:edit']"
            @click="handleEdit(row)"
          >
            编辑
          </ghost-button>
          <ghost-button
            v-if="
              row.status === '0' &&
              ['1', '4', '5', '9'].includes(row.todoType) &&
              (row.todoPersonId === userStore.userInfo?.userId || isAdmin)
            "
            danger
            @click="handleReject(row)"
          >
            驳回
          </ghost-button>
          <ghost-button
            v-if="row.status === '1'"
            v-access:code="['hm:todoItems:query']"
            @click="todoInfo(row, false)"
          >
            {{ $t('详情') }}
          </ghost-button>
          <ghost-button
            v-if="row.status === '1' && isLeader && row.todoType === '0'"
            v-access:code="['hm:todoItems:query']"
            @click="todoInfo(row, true)"
          >
            {{ $t('评价') }}
          </ghost-button>
          <Popconfirm
            v-if="isAdmin"
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['hm:todoItems:remove']"
              @click=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <TodoItemsModal @reload="tableApi.query()" />
    <TodoItemsInfoModal @reload="tableApi.query()" />
    <TodoDetailModal @reload="tableApi.query()" />
  </Page>
</template>
